package evidences

import (
  "context"
  "go.mongodb.org/mongo-driver/bson"
  "go.mongodb.org/mongo-driver/bson/primitive"
  "go.mongodb.org/mongo-driver/mongo/options"
  "livefind/db"
  "livefind/utils/logger"
)

type EvidenceInfo struct {
  ID           primitive.ObjectID `json:"id,omitempty" bson:"_id,omitempty"`
  CaseID       primitive.ObjectID `json:"caseId,omitempty" bson:"caseId,omitempty"`
  EvidenceNo   string             `json:"evidenceNo,omitempty" bson:"evidenceNo,omitempty"`
  EvidenceName string             `json:"evidenceName,omitempty" bson:"evidenceName,omitempty"`
  EvidenceType string             `json:"evidenceType,omitempty" bson:"evidenceType,omitempty"`
  OriginalPath string             `json:"originalPath,omitempty" bson:"originalPath,omitempty"`
  SavePath     string             `json:"savePath,omitempty" bson:"savePath,omitempty"`
}

type EvidencesModel struct {
}

func (em *EvidencesModel) FindEvidenceByFilter(filter bson.M) (evidenceInfo EvidenceInfo, err error) {
  evidenceMongo := db.Collection("cases", "evidence")

  ctx := context.TODO()
  err = evidenceMongo.FindOne(ctx, filter).Decode(&evidenceInfo)

  return evidenceInfo, err
}

func (em *EvidencesModel) Create(info EvidenceInfo) (err error) {
  evidenceMongo := db.Collection("cases", "evidence")

  ctx := context.TODO()
  _, err = evidenceMongo.InsertOne(ctx, &info)

  if err != nil {
    logger.Error(err.Error(), err)
  }
  return err
}

func (em *EvidencesModel) List(filter bson.M, skip, limit int) (evidencesInfo []EvidenceInfo, err error) {
  evidenceMongo := db.Collection("cases", "evidence")

  ctx := context.TODO()
  opts := options.Find()
  opts.SetSkip(int64(skip))
  opts.SetLimit(int64(limit))
  evidencesInfoCursor, err := evidenceMongo.Find(ctx, filter, opts)

  defer func() { _ = evidencesInfoCursor.Close(ctx) }()

  if err != nil {
    logger.Error(err.Error(), err)
    return nil, err
  }
  if err = evidencesInfoCursor.All(ctx, &evidencesInfo); err != nil {
    logger.Error(err.Error(), err)
    return nil, err
  }
  return evidencesInfo, err
}

func (em *EvidencesModel) CountDocuments(filter bson.M) (int64, error) {
  evidenceMongo := db.Collection("cases", "evidence")

  ctx := context.TODO()
  totalNum, err := evidenceMongo.CountDocuments(ctx, filter)

  if err != nil {
    logger.Error(err.Error(), err)
    return 0, err
  }
  return totalNum, err
}

func (cm *EvidencesModel) GetById(filter bson.M) (caseInfo EvidenceInfo, err error) {
  caseMongo := db.Collection("cases", "evidence")

  ctx:=context.TODO()
  err = caseMongo.FindOne(ctx, filter).Decode(&caseInfo)

  if err != nil {
    logger.Error(err.Error(), err)
    return EvidenceInfo{}, err
  }
  return caseInfo, err
}